package com.qf;

import com.qf.mapper.EmpMapper;
import com.qf.pojo.Emp;
import com.qf.utils.MyBatisUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

/**
 * 查询
 * @author lixu
 */
public class MybatisQuery {

    //声明
    SqlSessionFactory sqlSessionFactory = null;
    /**
     * Junit单元测试 公共代码提取
     */
    @Before
    public void before() throws Exception{

        //1:Mybatis使用的 23种设计模式中 工厂模式
        //1.1材料
        String resource = "mybatis-config.xml";
        //1.2 将上面的文件成流
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        //1.3:构建工厂对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder =
                new SqlSessionFactoryBuilder();
        //2：工厂对象
        sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);

    }
    /**
     * 序号参数绑定  查询
     */
    @Test
    public void findByQuery1(){

        SqlSession sqlSession = sqlSessionFactory.openSession();
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);

        //复杂查询
        List<Emp> empList = mapper.findByQuery1("王",18);
        empList.stream().forEach(System.out::println);
    }
    /**
     * 注解参数绑定  查询
     */
    @Test
    public void findByQuery2(){

        SqlSession sqlSession = sqlSessionFactory.openSession();
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        //复杂查询
        List<Emp> empList = mapper.findByQuery2("王",18);
        empList.stream().forEach(System.out::println);
    }

    @Test
    public void MybatisUtilsTest(){

        try {
            EmpMapper mapper = MyBatisUtils.getMapper(EmpMapper.class);

            List<Emp> empList = mapper.findByQuery1("王",18);
            empList.stream().forEach(System.out::println);

            MyBatisUtils.commit();
        } catch (Exception e) {
            MyBatisUtils.rollback();
        }
    }



}
